import { useEffect, useState, useCallback } from 'react';
import { Typography } from 'antd';
import Cookies from 'js-cookie';
import DataTable from './components/DataTable';
import DataTree, { updateTreeData } from './components/DataTree';
import SearchBar from './components/SearchBar';
import service from './service';
import {
  calcTableScrollHeight,
  decorateKey,
  decorateRowKey,
  getMemberIconByKey,
  getLowercase,
} from './utils';
import { DEFAULT_PAGE_SIZE, PREFIX } from './utils/consts';
import { renderCellText } from './utils/tableUtil';
import { getMessage } from '@inbiz/react';
const { Text } = Typography;

export default function UserTab(props: any) {
  const [positionTreeData, setPositionTreeData] = useState<any[]>([]);
  const [selectedKeys, _selectedKeys] = useState<string[]>([]);
  const [expandedKeys, _expandedKeys] = useState<string[]>([]);
  const [pageNum, _pageNum] = useState(1);
  const [pageSize, _pageSize] = useState(props.pageSize || DEFAULT_PAGE_SIZE);
  const [isChild, _isChild] = useState(true);
  const [total, _total] = useState(0);
  const [searchValue, _searchValue] = useState('');
  const [data, _data] = useState<any[]>([]);
  const [hasMore, _hasMore] = useState(true);
  const [loadingMore, _loadingMore] = useState(false);
  const totalPages = Math.ceil(total / pageSize);
  const {
    selectedRowKeys,
    multiple,
    setSelected,
    tabKey,
    height,
    topPositionIds,
    isUnique,
    forbiddenItems,
    collectivization,
    configEvents,
    departmentFilteringRules,
  } = props;

  const {
    getTopPositionList,
    getPositionList,
    getSubPositionList,
  } = service;

  const _getTopPositionList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onGetTopPositionsParams?.(params)) || params;
    const data = await (configEvents.current?.onGetTopPositionsRequest || getTopPositionList)(newParams as any);
    return await configEvents.current?.onGetTopPositionsData?.(data) || data;
  }, []);

  const _getPositionList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onGetPositionsParams?.(params)) || params;
    const data = await (configEvents.current?.onGetPositionsRequest || getPositionList)(newParams as any);
    return await configEvents.current?.onGetPositionsData?.(data) || data;
  }, []);

  const _getSubPositionList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onGetSubPositionsParams?.(params)) || params;
    const data = await (configEvents.current?.onGetSubPositionsRequest || getSubPositionList)(newParams as any);
    return await configEvents.current?.onGetSubPositionsData?.(data) || data;
  }, []);

  const decorateData = decorateKey(tabKey, (data) => {
    return {
      icon: getMemberIconByKey(tabKey, forbiddenItems.includes(data.id) ? true : false),
    };
  });

  const rowKey = decorateRowKey(tabKey);
  const getPositionId = (selKeys?: string[]) => {
    let keys = selKeys || selectedKeys;
    if (keys.length) {
      let key = keys[0];
      const [tabKey, positionId] = key.split('-');
      if (positionId) {
        return Number(positionId);
      }
    }
  };

  const onSearch = (value: string, checked: boolean) => {
    _searchValue(value);
    _isChild(checked);
    _getPositionList({
      positionId: getPositionId() as number,
      searchContent: value,
      isChild: checked,
      pageNum: 1,
      pageSize: pageSize,
      isContainSelf: collectivization ? true : topPositionIds.includes(getPositionId()),
    })
      .then((res) => {
        if (res.Info) {
          _data((getLowercase(res.Info, tabKey) || []).map(decorateData));
          _pageNum(1);
          _total(res.Total);
        }
      });
  };

  const onPagination = (pagination: { current: number; pageSize: number }) => {
    _getPositionList({
      positionId: getPositionId() as number,
      searchContent: searchValue,
      isChild: isChild,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      isContainSelf: collectivization ? true : topPositionIds.includes(getPositionId()),
    })
      .then((res) => {
        if (res.Info) {
          _data((getLowercase(res.Info, tabKey) || []).map(decorateData));
          _pageNum(pagination.current);
          _pageSize(pagination.pageSize);
          _total(res.Total);
        }
      });
  };

  const onSelect = (keys: string[], info: any) => {
    if (keys.length) {
      _selectedKeys(keys);
      const positionId = getPositionId(keys);
      if (positionId) {
        _getPositionList({
          positionId: positionId,
          searchContent: searchValue,
          isChild: isChild,
          pageNum: 1,
          pageSize: pageSize,
          isContainSelf: collectivization ? true : topPositionIds.includes(positionId),
        })
          .then((res) => {
            if (res.Info) {
              _data((getLowercase(res.Info, tabKey) || []).map(decorateData));
              _pageNum(1);
              _total(res.Total);
            }
          });
      }
    }
  };

  useEffect(() => {
    if (departmentFilteringRules != 'exceptSelected' || departmentFilteringRules == 'exceptSelected' && topPositionIds?.length == 1 && topPositionIds?.[0] == 1 || departmentFilteringRules == 'exceptSelected' && topPositionIds?.length == 0 || collectivization) {
      _getTopPositionList({
        positionIds: collectivization
          ? Cookies.get('orgIdentityId')
            ? [Cookies.get('orgIdentityId')]
            : [1]
          : departmentFilteringRules == 'exceptSelected' && topPositionIds?.length == 1 && topPositionIds?.[0] == 1 ? [] : departmentFilteringRules != 'exceptSelected' && topPositionIds?.length == 0 ? [1] : departmentFilteringRules == 'exceptSelected' && topPositionIds?.length == 0 ? [1] : topPositionIds,
      })
        .then((res) => {
          if (Array.isArray(res) && res.length) {
            const keys = [decorateData(getLowercase(res, tabKey)[0]).key];
            _selectedKeys(keys);
            _expandedKeys(keys);
            setPositionTreeData(getLowercase(res, tabKey).map(decorateData));
            service
              .getPositionList({
                positionId: getPositionId(keys) as number,
                searchContent: '',
                isChild: true,
                pageNum: 1,
                pageSize: pageSize,
                isContainSelf: true,
              })
              .then((res) => {
                if (res.Info) {
                  _data((getLowercase(res.Info, tabKey) || []).map(decorateData));
                  _pageNum(1);
                  _total(res.Total);
                }
              });
          }
        });
    } else {
      _getSubPositionList({
        positionId: 1,
        banPositionIds: topPositionIds,
      }).then((res) => {
        if (Array.isArray(res) && res.length) {
          const keys = [decorateData(getLowercase(res, tabKey)[0]).key];
          _selectedKeys(keys);
          _expandedKeys(keys);
          setPositionTreeData(getLowercase(res, tabKey).map(decorateData));
          service
            .getPositionList({
              positionId: getPositionId(keys) as number,
              searchContent: '',
              isChild: true,
              pageNum: 1,
              pageSize: pageSize,
              isContainSelf: true,
            })
            .then((res) => {
              if (res.Info) {
                _data((getLowercase(res.Info, tabKey) || []).map(decorateData));
                _pageNum(1);
                _total(res.Total);
              }
            });
        }
      });
    }
  }, []);

  return (
    <div className={`${PREFIX}-tab`}>
      <div className={`${PREFIX}-leftTree`}>
        <DataTree
          showIcon
          expandedKeys={expandedKeys}
          onExpand={(keys) => _expandedKeys(keys)}
          treeData={positionTreeData}
          loadData={(e) => {
            return _getSubPositionList({
              positionId: e.identityid,
              id: e.id,
            })
              .then((res) => {
                if (res) {
                  setPositionTreeData((list) => {
                    return updateTreeData(list, e.key, getLowercase(res, tabKey).map(decorateData));
                  });
                }
              });
          }}
          multiple={false}
          selectedKeys={selectedKeys}
          onSelect={onSelect}
        />
      </div>
      <div className={`${PREFIX}-rightContent`}>
        <SearchBar
          // 包含子职位
          checkLabel={getMessage('MemberSelect.lang.includingSubPosition')}
          // 输入职位名称
          placeholder={getMessage('MemberSelect.lang.enterPositionName')}
          defaultChecked={isChild}
          defaultValue={searchValue}
          onSearch={onSearch}
        />
        <DataTable
          rowSelection={{
            hideSelectAll: isUnique,
            getCheckboxProps: (r) => {
              return {
                disabled: forbiddenItems.includes(r.id),
              };
            },
          }}
          multiple={multiple}
          rowKey={rowKey}
          scroll={{
            scrollToFirstRowOnChange: true,
            y: calcTableScrollHeight(height, true),
          }}
          onRow={(item, index) => {
            return {
              onClick: (e) => {
                e.currentTarget
                  .querySelector(multiple ? '.ant-checkbox-wrapper' : '.ant-radio-wrapper')
                  ?.click();
                props.onRowClick?.(item, index);
              },
            };
          }}
          rowClassName={(r) => {
            if (forbiddenItems.includes(r.id)) {
              return 'datatable-forbidden-item';
            } else {
              return '';
            }
          }}
          pagination={{
            pageSize,
            current: pageNum,
            total,
          }}
          columns={[
            {
              // 职位名称
              title: <Text ellipsis={{ tooltip: true }}>{getMessage('MemberSelect.lang.positionName')}</Text>,
              dataIndex: 'name',
              key: 'name',
              render: renderCellText('name', true),
            },
            {
              // 部门
              title: <Text ellipsis={{ tooltip: true }}>{getMessage('MemberSelect.lang.personTabs.department')}</Text>,
              dataIndex: 'deptpathname',
              key: 'deptpathname',
              render: renderCellText('deptpathname', true),
            },
          ]}
          dataSource={data}
          onChange={onPagination}
          selectedRowKeys={selectedRowKeys}
          onSelectChange={(keys, rows) => {
            setSelected(keys, data);
          }}
        />
      </div>
    </div>
  );
}
